var variableArr = ['addProvider','materialCode', 'materialName', 'model', 'status', 'model', 'defaultWarehouse',
    'materialType', 'materialTypeSelect', 'providerName', 'unit', 'unitPrice', 'isEquals', 'isStock', 'color', 'colorDescription',
    'procurementCycles', 'stock', 'creater', 'creationTime', 'lastModifier', 'lastModifyTime', 'updateBtn',
    'modalMaterialName', 'modalModel', 'modalDefaultWarehouse', 'modalMaterialType', 'modalTypeSelect',
    'modalProviderName', 'modalUnit', 'modalUnitPrice', 'modalIsEquals', 'modalIsStock', 'modalColor',
    'modalColorDescription', 'modalProcurementCycles'
];
$(function () {
    page.bind();
//    uploadpic.init();
    //promise.all所有请求完毕后执行then()
    var index = layer.load(1,{shade:[0.5,"#000"]})
    Promise.all([page.getMaterialCode(),
        page.getMaterialName(),
        page.getModel(),
        page.getUnit(),
        page.getProviderName(),
        page.getMaterialType(),
        page.getRowMaterialType(),
        page.getColor()
    ]).then(function () {
    	layer.close(index);
    	page.saveNewMaterial();
        var materialCompanyVariable = window.sessionStorage.getItem('materialCompanyVariable');
        window.sessionStorage.removeItem('materialCompanyVariable');
        if (!materialCompanyVariable) {
            return;
        }
        materialCompanyVariable = JSON.parse(materialCompanyVariable);
        for (var i = 0; i < variableArr.length; i++) {
            var feild = variableArr[i];
            var value = materialCompanyVariable[feild];
            if(feild == "addProvider"){//是否打开模态框
            	if(value==2){
            		$("#addMaterialModal").modal("show");
            	}
            }else{
            	if (feild == "defaultWarehouse") {
            		if (value == "原材料仓") {
            			$("#materialType").css('display', 'none');
            			$("#materialTypeSelect").css('display', '');
            			$("#materialTypeSelect").val("请选择");
            		} else {
            			$("#materialType").css('display', '');
            			$("#materialTypeSelect").css('display', 'none');
            			$("#materialTypeSelect").val("");
            		}
            	}
            	if (feild == "modalDefaultWarehouse") {
            		if (value == "原材料仓") {
            			$("#modalMaterialType").css('display', 'none');
            			$("#modalTypeSelect").css('display', '');
            			$("#modalTypeSelect").val("请选择");
            		} else {
            			$("#modalMaterialType").css('display', '');
            			$("#modalTypeSelect").css('display', 'none');
            		}
            	}
            	$("#" + variableArr[i]).val(value);
            }
        }
        var customerName =  window.sessionStorage.getItem("customerName");
        if(customerName!==undefined&&customerName!==null&&customerName.trim()!==''){
        	$("#modalProviderName").filterSelect("setValue",customerName);
        	window.sessionStorage.removeItem("customerName");
        }
    });
    
    queryMaterial();
});
//var urlPre = "http://8888.shinehao.net/";
//var urlPre = "http://localhost:8080/";
function upload(imageId,cropedBigImgId){
	var form = new FormData;//创建一个FormData对象  
    form.append('file',$("#"+imageId).get(0).files[0]);//将文件放到FormData对象中  
    $.ajax({  
        url : "/weixin/basicData/uploadPic",//访问路径  
        contentType: false,
        processData: false,
        type:"post",  
        data :form,  
        dataType : "json"  
    }).success(function(data,status){  
    	console.log(data);
    	console.log(status);
        if(status=="success"){  
            if(data.result==true){
            	var domain = window.location.host;//获取当前域名 tips：(http://)localhost:8080(/)
            
            	console.log(domain);
            	console.log(data.data);
                $("#"+cropedBigImgId).attr('src',data.data.indexOf("http")>-1?data.data:"http://"+domain+data.data); 
            }  else{
            	alert("文件上传失败");  
            }
        }   
    }).error(function(){  
        alert("服务器未响应");  
    });  
};
var page = {
    bind: function () {
    	$('#chooseImage').on('change',function(){  
            var filePath = $(this).val(),         //获取到input的value，里面是文件的路径  
                fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(); //文件名后缀 
            // 检查是否是图片  
            if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {  
                alert('上传错误,文件格式必须为：png/jpg/jpeg');  
                return false;
            }  
            upload("chooseImage","cropedBigImg");
    	});   
    	$('#modal-chooseImage').on('change',function(){  
    		var filePath = $(this).val(), 
    			fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(); 
    		// 检查是否是图片  
    		if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {  
    			alert('上传错误,文件格式必须为：png/jpg/jpeg');  
    			return false;
    		}  
    		upload("modal-chooseImage","modal-cropedBigImg");
    	});   
    	$("#modalMaterialName,#modalModel,#modalProviderName,#modalColor").bind("blur",function(){
    		var materialName = $("#modalMaterialName").val();
    		var model = $("#modalModel").val();
    		var providerName = $("#modalProviderName").val();
    		var color = $("#modalColor").val();
    		console.log("materialName:"+materialName+" model:"+model+" providerName:"+providerName+" color:"+color);
    		if(materialName!='' && model!='' && providerName!='请选择'){
    			ajaxUtil.ajaxRequest("basicData/getMaterialInfo",
    					{'materialName':materialName,'model':model,'providerName':providerName,'color':color})
    					.then(function(data){
    						console.log(data);
    						if(data!=null){
    							$("#modalColorDescription").val(data.colorDescription);
    							$("#modalDefaultWarehouse").val(data.defaultWarehouse);
    							if (data.defaultWarehouse == "原材料仓") {
    		                        $("#modalMaterialType").css('display', 'none');
    		                        $("#modalTypeSelect").css('display', '');
    		                    } else {
    		                        $("#modalMaterialType").css('display', '');
    		                        $("#modalTypeSelect").css('display', 'none');
    		                    }
    							$("#modalUnit").val(data.unit);
    							$("#modalUnitPrice").val(data.unitPrice);
    							$("#modalIsEquals").val(data.isEquals);
    							$("#modalIsStock").val(data.isStock);
    							$("#modalProcurementCycles").val(data.procurementCycles);
    							$("#modalColorDescription").attr("disabled","true");
    							$(".input-info").attr("disabled","true");
    						}else{
    							$("#modalDefaultWarehouse").val("");
    							$("#modalUnit").val("");
    							$("#modalUnitPrice").val("");
    							$("#modalIsEquals").val("");
    							$("#modalIsStock").val("");
    							$("#modalProcurementCycles").val("");
    							$(".input-info").removeAttr("disabled");
    						}
    					});
    		}
    	});
        $(".addProvider").bind('click', function () {
            var materialCompanyVariable = {};
            var data_value = $(this).attr("data-value");
            for (var i = 0, l = variableArr.length; i < l; i++) {
            	if(variableArr[i]=="addProvider"){
            		materialCompanyVariable[variableArr[i]] = data_value;
            	}else{
            		materialCompanyVariable[variableArr[i]] = $("#" + variableArr[i]).val();
            	}
            }
            window.sessionStorage.setItem('materialCompanyVariable', JSON.stringify(materialCompanyVariable));
            window.location.href = "customers.html?add="+data_value;
        });
        //点击切换查看状态按钮
        $("#view").bind("click", function () {
            var view = $("#view").val();
            if (view == "1") {
                view = "0";
            } else {
                view = "1";
            }
            queryMaterial(view);
            $("#view").val(view);
        });
        //改变模态框默认仓库时，如果为原材料仓显示select，否则显示input
        $("#modalDefaultWarehouse").bind("change", function () {
            var val = $("#modalDefaultWarehouse").val();
            //用户之前输入的物料类型值
            var modelMaterialTypeVal = $("#modalMaterialType").val().trim();
            if (val == "原材料仓") {
                $("#modalMaterialType").css('display', 'none');
                $("#modalTypeSelect").css('display', '');
                if(modelMaterialTypeVal!==''){ 
	               var options =  $("#modalTypeSelect option");
	               for(var i=0;i<options.length;i++){
	                   var selectVal = options[i].label; 
	                   if(selectVal!==undefined && selectVal===modelMaterialTypeVal){
	                	   $("#modalTypeSelect").val(modelMaterialTypeVal);
	                	   break;
	                   }else{ 
	                	   $("#modalTypeSelect").val("请选择");
	                   }
	                };
                }else{
                	$("#modalTypeSelect").val("请选择");
                }
            } else {
                $("#modalMaterialType").css('display', '');
                $("#modalTypeSelect").css('display', 'none');
            }
        });
        //改变默认仓库时，如果是原材料仓，则隐藏新增物料类型按钮，否则显示
        $("#defaultWarehouse").bind("change", function () {
            var val = $("#defaultWarehouse").val();
            //用户之前输入的物料类型值
            var materialTypeVal = $("#materialType").val().trim();
            if (val == "原材料仓") {
                $("#materialType").css('display', 'none');
                $("#materialTypeSelect").css('display', '');
                if(materialTypeVal!==''){ 
 	               var options =  $("#materialTypeSelect option");
 	               for(var i=0;i<options.length;i++){
 	                   var selectVal = options[i].label; 
 	                   if(selectVal!==undefined && selectVal===materialTypeVal){
 	                	   $("#materialTypeSelect").val(materialTypeVal);
 	                	   break;
 	                   }else{ 
 	                	   $("#materialTypeSelect").val("请选择");
 	                   }
 	                };
                 }else{
                 	$("#materialTypeSelect").val("请选择");
                 }
            } else {
                $("#materialType").css('display', '');
                $("#materialTypeSelect").css('display', 'none');
                $("#materialTypeSelect").val("");
            }
        });
        //当仓库为原材料仓，改变物料类型时，PC、TR、塑钢、板材、肶套默认计价单位为不同；否则默认相同
        $("#materialTypeSelect").bind("change", function () {
            var typeValue = $(this).val();
            if (typeValue.indexOf("PC") > -1 || typeValue.indexOf("TR") > -1 || typeValue.indexOf("塑钢") > -1 || typeValue.indexOf("板材") > -1 || typeValue.indexOf("肶套") > -1) {
                $("#isEquals").val("0");
            } else {
                $("#isEquals").val("1");
            }
            if(typeValue.indexOf("板材")>-1){
                $("#materialName").val("胶板料");
                $("#materialName").attr("readonly","readonly");
            }else{
//            	if($("#materialName").val()=="胶板料"){
//            		$("#materialName").val("");
//            	}
//                $("#materialName").removeAttr("readonly");
            }
            if(typeValue=="镜片"){
            	$("#transTr").css("display","");
            }else{
            	$("#transTr").css("display","none");
            }
        });
        $("#modalTypeSelect").bind("change", function () {
            var typeValue = $(this).val();
            if (typeValue.indexOf("PC") > -1 || typeValue.indexOf("TR") > -1 || typeValue.indexOf("塑钢") > -1 || typeValue.indexOf("板材") > -1 || typeValue.indexOf("肶套") > -1) {
                $("#modalIsEquals").val("0");
            } else {
                $("#modalIsEquals").val("1");
            }
            if(typeValue.indexOf("板材")>-1){
                $("#modalMaterialName").val("胶板料");
                $("#modalMaterialName").attr("readonly","readonly");
            }else{
            	if($("#modalMaterialName").val()=="胶板料"){
            		$("#modalMaterialName").val("");
            	}
                $("#modalMaterialName").removeAttr("readonly");
            }
            if(typeValue=="镜片"){
            	$("#modal-transTr").css("display","");
            }else{
            	$("#modal-transTr").css("display","none");
            }
        });
        
        //改变单位时 如果单位为付,生产单位与计价单位相同
        $("#modalUnit").bind("change",function(){
        	var unitVal = $(this).val();
        	if(unitVal==="付"){
        		$("#modalIsEquals").val(1);
        		$("#modalIsEquals").attr("disabled",true);
        	}else{
        		$("#modalIsEquals").val(0); 
        		$("#modalIsEquals").attr("disabled",true);
        	}
        })
        //调用模态框show方法后触发
        $('#addMaterialModal').on('show.bs.modal', function () {
            $("#modalStock").bind('blur', function () {
                var stock = $("#modalStock").val();
                if (stock != "" && /^\d+(\.\d{0,2})?$/.test(stock) == false || parseFloat(stock) >= parseFloat(10000000000)) {
                    layAlert("库存数量格式错误");
                    $("#modalStock").val("");
                    return false;
                }
            });
        });
        //模态框隐藏后
        $('#addMaterialModal').on('hidden.bs.modal', function () {
            $(this).removeData("bs.modal");
        });
        //模态框点击添加按钮时
        $("#add").bind("click", function () {
        	var object = page.insertParam();
        	if (!object) { 
                return false; 
            }  
        	ajaxUtil.ajaxRuquest(
                'basicData/insertCompanyMaterial',
                object,
                function (data) {
                    table.ajax.reload(null, false);
                    page.getMaterialCode();
                    page.getMaterialName();
                    page.getModel();
                    page.getUnit();
                    page.getProviderName();
                    page.getMaterialType();
                    page.getColor();
                    layAlert("添加成功!"); 
                    $("#addMaterialModal").modal("hide");
                    //跳转会生成物料采购单页面
                    page.toPurchaseWarehousePage(data[0].id,object.providerName);
                	 
                }
            );
           
        })
        //模态框编号改变时
        $("#modalColor").bind("change", function () {
            var color = $("#modalColor").val()
            ajaxUtil.ajaxRuquest(
                'basicData/getCompanyColorDescription', {
                    'color': color
                },
                function (data) {
                    if (data != "") {
                        //根据编号能查找到数据时
                        $("#modalColorDescription").val(data);
                        $("#modalColorDescription").attr("disabled","true");
                    } else {
                        //查不到数据时
                        $("#modalColorDescription").val("");
                        $("#modalColorDescription").removeAttr("disabled");
                    }
                }
            );
        });
        //改变物料代码时
        $("#materialCode").bind("change", function () {
            var materialCode = $("#materialCode").val();
            page.getMaterialDetail(materialCode);
        });
        //改变编号时
        $("#color").bind("change", function () {
            var color = $("#color").val();
            //连带获取描述
            page.getColorDescription(color);
        });
        //点击+物料名称按钮时
        $("#addMaterialNameBtn").bind("click", function () {
            $("#addMaterialNameTr").show("slow");
        });
        //点击添加物料名称按钮时
        $("#addMaterialNameBtn2").bind("click", function () {
            var addMaterialName = $("#addMaterialName").val();
            if (addMaterialName == "") {
                layAlert("请输入要添加的物料名称");
                return false;
            } else {
                $("#addMaterialNameTr").hide("slow");
                $("#materialName").append("<option value=" + addMaterialName + ">" + addMaterialName + "</option>");
                $("#materialName option[value='" + addMaterialName + "']").attr("selected", "selected");
            }
        });
        //点击+规格型号按钮时
        $("#addModelBtn").bind("click", function () {
            $("#addModelTr").show("slow");
        });
        //点击添加规格型号按钮时
        $("#addModelNameBtn").bind("click", function () {
            var addModelName = $("#addModelName").val();
            if (addModelName == "") {
                layAlert("请输入要添加的规格型号");
                return false;
            } else {
                $("#addModelTr").hide("slow");
                $("#model").append("<option value=" + addModelName + ">" + addModelName + "</option>");
                $("#model option[value='" + addModelName + "']").attr("selected", "selected");
            }
        });
        //点击+单位按钮时
        $("#addUnitBtn").bind("click", function () {
            $("#addUnitBTr").show("slow");
        });
        //点击添加单位按钮时
        $("#addUnitNameBtn").bind("click", function () {
            var addUnitName = $("#addUnitName").val();
            if (addUnitName == "") {
                layAlert("请输入要添加的单位");
                return false;
            } else {
                $("#addUnitBTr").hide("slow");
                $("#unit").append("<option value=" + addUnitName + ">" + addUnitName + "</option>");
                $("#unit option[value='" + addUnitName + "']").attr("selected", "selected");
            }
        });
        //点击+默认仓库按钮时
        $("#addDefaultWarehouseBtn").bind("click", function () {
            $("#addDefaultWarehouseTr").show("slow");
        });
        //点击添加默认仓库按钮时
        $("#addDefaultWarehouseNameBtn").bind("click", function () {
            var addDefaultWarehouseName = $("#addDefaultWarehouseName").val();
            if (addDefaultWarehouseName == "") {
                layAlert("请输入要添加的默认仓库");
                return false;
            } else {
                $("#addDefaultWarehouseTr").hide("slow");
                $("#defaultWarehouse").append("<option value=" + addDefaultWarehouseName + ">" + addDefaultWarehouseName + "</option>");
                $("#defaultWarehouse option[value='" + addDefaultWarehouseName + "']").attr("selected", "selected");
            }
        });
        //点击+供应商名称按钮时
        $("#addProviderNameBtn").bind("click", function () {
            $("#addProviderNameTr").show("slow");
        });
        //点击添加供应商名称按钮时
        $("#addProviderNameBtn2").bind("click", function () {
            var addProviderName = $("#addProviderName").val();
            if (addProviderName == "") {
                layAlert("请输入要添加的供应商名称");
                return false;
            } else {
                $("#addProviderNameTr").hide("slow");
                $("#providerName").append("<option value=" + addProviderName + ">" + addProviderName + "</option>");
                $("#providerName option[value='" + addProviderName + "']").attr("selected", "selected");
            }
        });
        //点击+物料类型按钮时
        $("#addMaterialTypeBtn").bind("click", function () {
            $("#addMaterialTypeTr").show("slow");
        });
        //点击添加物料类型按钮时
        $("#addMaterialTypeNameBtn").bind("click", function () {
            var addMaterialTypeName = $("#addMaterialTypeName").val();
            if (addMaterialTypeName == "") {
                layAlert("请输入要添加的物料类型");
                return false;
            } else {
                $("#addMaterialTypeTr").hide("slow");
                $("#materialType").append("<option value=" + addMaterialTypeName + ">" + addMaterialTypeName + "</option>");
                $("#materialType option[value='" + addMaterialTypeName + "']").attr("selected", "selected");
            }
        });
        //点击修改按钮时
        $("#updateBtn").bind("click", function () {
            var object = page.updateParam();
        	if (!object) {
                return false; 
            } 
            ajaxUtil.ajaxRuquest(
                'basicData/updateCompanyMaterial',
                page.updateParam(),
                function (data) {
                    page.getMaterialCode();
                    table.ajax.reload(null, false);
                    layAlert("修改成功");
                }
            );
        });
    },
    saveNewMaterial:function(){
    	var data = requestUtil.getRequest();
		if(data.saveNewMaterial==="2"){
			$("#addMaterialModal").modal("show"); 
		}
    },
    toPurchaseWarehousePage:function(materialId,providerName){
    	var data = requestUtil.getRequest();
		if(data.saveNewMaterial==="2"){ 
			sessionStorage.setItem("providerName",providerName);
//			location.href="purchaseWarehoseOrder.html?saveNewMaterial=3&materialId="+materialId;
			location.href="purchaseOrder/createWarehouse/index.html?saveNewMaterial=3&materialId="+materialId;
		}
    }, 
    //获取物料代码
    getMaterialCode: function () {
        return ajaxRequest('basicData/getCompanyMaterialCode', {}).then(function (data) {
            var html = "<option>请选择</option>";
            for (var i = 0; i < data.length; i++) {
                html = html + "<option value='" + data[i].id + "'>" + data[i].materialCode + "</option>"
            }
            $("#materialCode").html("");
            $("#materialCode").append(html);
        });
    },
    //获取物料名称
    getMaterialName: function () {
        return ajaxRequest('basicData/getCompanyMaterialName', {}).then(function (data) {
            var html = "";
            for (var i = 0; i < data.length; i++) {
                html = html + "<option value='" + data[i] + "'/>";
            }
            $("#materialNameList").html("");
            $("#materialNameList").append(html);
        });
    },
    //获取规格型号
    getModel: function () {
        return ajaxRequest('basicData/getCompanyModel', {}).then(function (data) {
            var html = "";
            for (var i = 0; i < data.length; i++) {
                html = html + "<option value='" + data[i] + "'/>";
            }
            $("#modelList").html("");
            $("#modelList").append(html);
        });
    },
    //获取单位
    getUnit: function () {
        return ajaxRequest('basicData/getCompanyUnit', {}).then(function (data) {
            var html = "<option>请选择</option>";
            for (var i = 0; i < data.length; i++) {
                html = html + "<option value='" + data[i] + "'>" + data[i] + "</option>";
            }
            $("#unit").html("");
            $("#unit").append(html);
            $("#modalUnit").html("");
            $("#modalUnit").append(html);
        });
    },
    //获取供应商名称
    getProviderName: function () {
        return ajaxRequest('basicData/getCustomerName', {
            'view': '1'
        }).then(function (data) {
            var html = "<option>请选择</option>";
            for (var i = 0; i < data.length; i++) {
            	var customerName = data[i].customerName.trim();
                html = html + "<option value='" + customerName + "'>" + customerName + "</option>";
            }
            $("#providerName").html("");
            $("#providerName").append(html);           
			var option = {
					data:_.map(data,function(d){
						if(d===null){
							d.customerName = '';
						}
						return {
							id:d.customerName,
							name:d.customerName
						} 
					}),
					valueField:"id", 
					labelField:"name" 
			}  
			$("#modalProviderName").filterSelect("destroy");
			$("#modalProviderName").filterSelect(option);
        });
    },
    //获取物料类型
    getMaterialType: function () {
        return ajaxRequest('basicData/getCompanyMaterialType', {}).then(function (data) {
            var html = "";
            for (var i = 0; i < data.length; i++) {
                html = html + "<option value='" + data[i] + "'/>";
            }
            $("#materialTypeList").html("");
            $("#materialTypeList").append(html);
        });
    },
    //获取公共的物料类型写入原材料仓选项
    getRowMaterialType: function () {
        return ajaxRequest('basicData/getRowMaterialType', {}).then(function (data) {
            var html = "<option>请选择</option>";
            for (var i = 0; i < data.length; i++) {
                html += "<option value='" + data[i] + "'>" + data[i] + "</option>";
            }
            $("#modalTypeSelect").html("");
            $("#modalTypeSelect").append(html);
            $("#materialTypeSelect").html("");
            $("#materialTypeSelect").append(html);
        });
    },
    //获取编号
    getColor: function () {
        return ajaxRequest('basicData/getCompanyColor', {}).then(function (data) {
        	/*var list = _.map(data,function(d){
        		return {
        			label:d
        		};
        	});
        	$("#color").filterSelect({
        		data:list,
        		valueField:"label",
        		labelField:"label"
        	});*/
        	
            var html = "";
            for (var i = 0; i < data.length; i++) {
                html = html + "<option value='" + data[i] + "'/>";
            }
            $("#colorList").html("");
            $("#colorList").append(html);
        });
    },
    //根据编号获取描述
    getColorDescription: function (color) {
        ajaxUtil.ajaxRuquest(
            'basicData/getCompanyColorDescription', {
                'color': color
            },
            function (data) {
                if (data != "") {
                    //根据编号能查找到数据时
                    $("#colorDescription").val(data);
                    $("#colorDescription").attr("disabled","true");
                } else {
                    //查不到数据时
                    $("#colorDescription").val("");
                    $("#colorDescription").removeAttr("disabled");
                }
            }
        );
    },
    //获取物料详情
    getMaterialDetail: function (id) {
        ajaxUtil.ajaxRuquest( 
            'basicData/getCompanyMaterialDetail', {
                'id': id
            },
            function (data) {
                if (data != "") { 
                    //根据物料代码能查找到数据时
                    $("#updateBtn").val(id);
                    $("#materialCode").val(id);
                    //修改时物料代码不可修改
                    $("#materialCode").attr("disabled",true);
                    $("#materialName").val(data[0].materialName);
                    $("#materialName").attr("disabled",true);
//                    var file = $("#chooseImage");   
//                    file.after(file.clone());   
//                    file.remove();  
                    $("#cropedBigImg").attr("src",data[0].img);
                    $("#material").val(data[0].material);
                    $("#model").val(data[0].model);
                    //修改时规格不可修改
                    $("#model").attr("readonly","readonly");
                    $("#unit").val(data[0].unit);
                    var unitVal = $("#unit").val(); 
                    if(unitVal!==null && unitVal!=='' && unitVal!=='请选择' ){
                    	$("#unit").attr("disabled",true); 
                    } else{
                    	$("#unit").attr("disabled",false); 

                    }
                    $("#unitPrice").val(data[0].unitPrice);
                    $("#status").val(data[0].status);
                    $("#defaultWarehouse").val(data[0].defaultWarehouse);
                    if (data[0].defaultWarehouse == "原材料仓") {
                        $("#materialType").css('display', 'none');
                        $("#materialTypeSelect").css('display', '');
                        $("#materialTypeSelect").val(data[0].materialType);
                        if(data[0].materialType.indexOf("板材")>-1 && $("#materialName").val()=="胶板料"){
                            $("#materialName").attr("readonly","readonly");
                        }else{
                            $("#materialName").removeAttr("readonly");
                        }
                        if(data[0].materialType=="镜片"){
                        	$("#transTr").show();
                        	$("#transmittance").val(data[0].transmittance);
                        }else{
                        	$("#transTr").hide();
                        }
                        $("#materialTypeSelect").attr("disabled",true);
                    } else {
                        $("#materialType").css('display', '');
                        $("#materialTypeSelect").css('display', 'none');
                        $("#materialType").val(data[0].materialType);
                        $("#materialType").attr("disabled",true);
                    }
                    $("#defaultWarehouse").attr("disabled",true);
                    $("#providerName").val(data[0].providerName.trim());
                    //修改时供应商不可修改 
                    $("#providerName").attr("disabled",true);
                    //修改时编号不可修改
                    $("#color").val(data[0].color); 
                    $("#color").attr("readonly","readonly");
                    $("#colorDescription").val(data[0].colorDescription);
                    $("#colorDescription").attr("disabled",true);
                    $("#procurementCycles").val(data[0].procurementCycles);
                    $("#creater").val(data[0].creater);
                    $("#creationTime").val(data[0].creationTime);
                    $("#lastModifier").val(data[0].lastModifier);
                    $("#lastModifyTime").val(data[0].lastModifyTime);
                    $("#isEquals").val(data[0].isEquals);
                    $("#isStock").val(data[0].isStock===-1?1:data[0].isStock);
                    $("#stock").val(data[0].count);
                    $("#safetyStockMax").val(data[0].safetyStockMax);
                    $("#safetyStockMax").attr("disabled",false);
                    $("#safetyStockMin").val(data[0].safetyStockMin);
                    $("#safetyStockMin").attr("disabled",false);
                }
            }
        ); 
    },
    updateParam: function () {
        var id = $("#updateBtn").val();
        var materialCode = $("#materialCode option:selected").text().trim();
        var materialName = $("#materialName").val().trim();
        var materialPic = $("#cropedBigImg").attr("src");
        if(materialPic!==undefined){
        	if(materialPic!==null){
        		materialPic = materialPic.trim();
        	}
        }else{
        	materialPic = null; 
        }
        var model = $("#model").val().trim();
        var material = $("#material").val().trim();
        var unit = $("#unit").val().trim();
        var unitPrice = $("#unitPrice").val().trim();
        var isEquals = $("#isEquals").val();
        var isStock = $("#isStock").val();
        var status = $("#status").val();
        var defaultWarehouse = $("#defaultWarehouse").val().trim();
        if(defaultWarehouse===""){
        	layAlert("请选择仓库");
        	return false; 
        }
        var materialType;
        var transmittance;
        if (defaultWarehouse == "原材料仓") {
            materialType = myTrim($("#materialTypeSelect").val());
            if(materialType=="镜片"){
            	transmittance = myTrim($("#transmittance").val());
            	if(transmittance==""){
                	layAlert("请填写透光率");
                    return false;
                }
                if(isNaN(transmittance)){
                	layAlert("透光率应为数值");
                	return false;
                }
                if(parseInt(transmittance)<0 || parseInt(transmittance)>100){
                	layAlert("透光率取值范围为0-100");
                	return false;
                }
            }
        } else {
            materialType = myTrim($("#materialType").val());
        }
        var providerName = myTrim($("#providerName").val());
        var color = myTrim($("#color").val());
//        var color = $("#color").filterSelect("getValue");
        var colorDescription = myTrim($("#colorDescription").val());
        var procurementCycles = myTrim($("#procurementCycles").val());
        var chooseImage = $("#chooseImage").val();
        var cropedBigImg = $("#cropedBigImg").val();
        var safetyStockMax = $("#safetyStockMax").val().trim();
        var safetyStockMin = $("#safetyStockMin").val().trim();
        var sendData = {
            'id': id,
            'materialCode': materialCode,
            'materialName': materialName,
            'img':materialPic,
            'model': model,
            'material':material,
            'unit': unit,
            'unitPrice': unitPrice,
            'isEquals': isEquals,
            'isStock': isStock,
            'status': status,
            'defaultWarehouse': defaultWarehouse,
            'providerName': providerName,
            'materialType': materialType,
            'transmittance':transmittance,
            'color': color,
            'colorDescription': colorDescription,
            'procurementCycles': procurementCycles,
            'safetyStockMax':safetyStockMax,
            'safetyStockMin':safetyStockMin
        }
        if (sendData.materialName == "") {
            layAlert("请选择物料名称");
            return false;
        }
        if (sendData.model == "请选择") {
            layAlert("请选择规格型号");
            return false;
        }
        if (sendData.status == "请选择") {
            layAlert("请选择状态");
            return false;
        }
        if (sendData.defaultWarehouse == "请选择") {
            layAlert("请选择默认仓库");
            return false;
        }
        if (sendData.materialType == "" || sendData.materialType == "请选择") {
            layAlert("请填写物料类型");
            return false;
        }
        if (sendData.providerName == "请选择" || sendData.providerName ==="") {
            layAlert("请选择供应商名称");
            return false;
        }
        if (sendData.unit == "请选择") {
            layAlert("请选择单位");
            return false;
        }
        if (sendData.unitPrice != "" && /^\d+(\.\d+)?$/.test(sendData.unitPrice) == false) { //非负浮点数
            layer.msg("单价格式不符合规范");
            return false;
        }
        if(Number(sendData.unitPrice)>999999){
          	 layer.msg("单价最大是"+999999);
              return false;
        }
        if (sendData.isEquals == "" || sendData.isEquals == null) {
            layAlert("请选择计价单位是否和生产单位相同");
            return false;
        }
        if (sendData.isStock == "" || sendData.isStock == null) {
            layAlert("请选择是否可库存");
            return false;
        }
        if (sendData.procurementCycles != "" && /^[1-9]\d*$/.test(sendData.procurementCycles) == false) {
            layer.msg("采购周期只能是正整数");
            return false;
        }
        if(sendData.safetyStockMax != "" && /^[1-9]\d*$/.test(sendData.safetyStockMax) == false){
       	 layer.msg("安全库存上限只能是正整数");
            return false;
        }
        if(Number(sendData.safetyStockMax)>9999999999){
       	 layer.msg("安全库存上限最大是"+9999999999);
            return false;
        }
       if(sendData.safetyStockMin != "" && /^[1-9]\d*$/.test(sendData.safetyStockMin) == false){
      	    layer.msg("安全库存下限只能是正整数");
           return false;
       } 
       if(Number(sendData.safetyStockMin)>9999999999){
         	 layer.msg("安全库存下限最大是"+9999999999);
              return false;
         }
       if(sendData.safetyStockMax != "" && sendData.safetyStockMin != ""){
	       	if(Number(sendData.safetyStockMax)<Number(sendData.safetyStockMin)){
	       		layer.msg("安全库存上限不能小于安全库存下限"); 
	               return false;
	       	}
       }
        
        return sendData;
    },
    insertParam: function () {
        var materialName = $("#modalMaterialName").val().trim();
        var materialPic = $("#modal-cropedBigImg").attr("src");
        var model = $("#modalModel").val().trim();
        var material = $("#modal-material").val().trim();
        var unit = $("#modalUnit").val().trim();
        var unitPrice = $("#modalUnitPrice").val().trim();
        var isEquals = $("#modalIsEquals").val().trim();
        var isStock = $("#modalIsStock").val();
        var defaultWarehouse = $("#modalDefaultWarehouse").val();
        if(defaultWarehouse===""){
        	layAlert("请选择仓库");
        	return false;
        }
        var materialType;  
        var transmittance;
        if (defaultWarehouse == "原材料仓") {
            materialType = $("#modalTypeSelect").val().trim();
            if(materialType=="镜片"){
            	transmittance = myTrim($("#modal-transmittance").val());
            	if(transmittance==""){
            		layAlert("请填写透光率");
            		return false;
            	}
            	if(isNaN(transmittance)){
            		layAlert("透光率应为数值");
            		return false;
            	}
            	if(parseInt(transmittance)<0 || parseInt(transmittance)>100){
            		layAlert("透光率取值范围为0-100");
            		return false;
            	}
            }
        } else {
            materialType = $("#modalMaterialType").val().trim();
        }
        var providerName = $("#modalProviderName").filterSelect("getValue").trim();
        var color = $("#modalColor").val().trim();
        var colorDescription = $("#modalColorDescription").val().trim();
        var procurementCycles = $("#modalProcurementCycles").val().trim();
        var safetyStockMax = $("#modalSafetyStockMax").val().trim();
        var safetyStockMin = $("#modalSafetyStockMin").val().trim();
        var sendData = {
            'materialName': materialName,
            'img':materialPic,
            'model': model,
            'material':material,
            'unit': unit,
            'unitPrice': unitPrice,
            'isEquals': isEquals,
            'isStock': isStock,
            'defaultWarehouse': defaultWarehouse,
            'providerName': providerName,
            'materialType': materialType,
            'transmittance':transmittance,
            'color': color,
            'colorDescription': colorDescription,
            'procurementCycles': procurementCycles,
            'safetyStockMax':safetyStockMax,
            'safetyStockMin':safetyStockMin
        }
        if (sendData.materialName == "") {
            layAlert("请填写物料名称");
            return false;
        }
        if (sendData.model == "") {
            layAlert("请填写规格型号");
            return false;
        }
        if (sendData.defaultWarehouse == "请选择") {
            layAlert("请选择默认仓库");
            return false;
        }
        if (sendData.materialType == "" || sendData.materialType == "请选择") {
            layAlert("请填写物料类型");
            return false;
        }
        
        if (sendData.providerName == "请选择" || sendData.providerName ==="") {
            layAlert("请选择供应商名称");
            return false;
        }
        if (sendData.unit == "请选择") {
            layAlert("请选择单位");
            return false;
        }
        if (sendData.unitPrice != "" && /^\d+(\.\d+)?$/.test(sendData.unitPrice) == false) { //非负浮点数
            layer.msg("单价格式不符合规范");
            return false;
        }
        if(Number(sendData.unitPrice)>999999){
         	 layer.msg("单价最大是"+999999);
             return false;
       }
        if (sendData.isEquals == "" || sendData.isEquals == null) {
            layAlert("请选择计价单位是否和生产单位相同");
            return false;
        }
        if (sendData.isStock == "" || sendData.isStock == null) {
            layAlert("请选择是否可库存");
            return false;
        }
        if (sendData.procurementCycles != "" && /^[1-9]\d*$/.test(sendData.procurementCycles) == false ) { //正整数
            layer.msg("采购周期只能是正整数");
            return false;
        }
        if(sendData.safetyStockMax != "" && /^[1-9]\d*$/.test(sendData.safetyStockMax) == false && Number(sendData.safetyStockMax)<=0){
        	 layer.msg("安全库存上限只能是正整数");
             return false;
        }
        if(Number(sendData.safetyStockMax)>9999999999){
        	 layer.msg("安全库存上限最大是"+9999999999);
             return false;
        }
        if(sendData.safetyStockMin != "" && /^[1-9]\d*$/.test(sendData.safetyStockMin) == false && Number(sendData.safetyStockMin)<=0){
       	    layer.msg("安全库存下限只能是正整数");
            return false;
        }
        if(Number(sendData.safetyStockMin)>9999999999){
       	 layer.msg("安全库存下限最大是"+9999999999);
            return false;
       }
        if(sendData.safetyStockMax != "" && sendData.safetyStockMin != ""){
        	if(Number(sendData.safetyStockMax)<Number(sendData.safetyStockMin)){
        		layer.msg("安全库存上限不能小于安全库存下限"); 
                return false;
        	}
        }
        return sendData;
    }
}

function myTrim(x) {
    return x.replace(/^\s+|\s+$/gm, '');
}

function ajaxRequest(url, data) {
    if (data === undefined) {
        data = {};
    }
    return new Promise(function (resole, reject) {
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (res) {
                var result = res.result;
                if (!result) {
                    reject();
                    return;
                }
                var data = res.data;
                resole(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                reject({
                    textStatus: textStatus,
                    errorThrown: errorThrown
                });
            }
        });
    });
}

var tableData = []; //查询物料结果
//查询公司物料表
var table;

function queryMaterial() {
    $('#queryMaterialTable tbody').unbind("click");
    $('#queryMaterialTable').dataTable().fnDestroy();
    table = $('#queryMaterialTable').DataTable({
        "ajax": {
            "url": "basicData/queryMaterialCompany",
            "dataSrc": "returnData",
            "data": {},
        }, 
        "columns": [{
                "data": "materialName"
            },
            {
                "data": "materialType"
            }, 
            {
                "data": "status"
            }, 
            {
                "data": "color"
            },
            {
                "data": "model"
            },
            {
                "data": "providerName"
            },
            {
                "data": "colorDescription"
            }
        ],
        "processing": true, //打开数据加载时的等待效果
        //	      "serverSide": true,//打开后台分页
        "pagingType": "full_numbers", //设置分页控件的模式
        "aLengthMenu": [20], //设置一页展示多少条记录
        "ordering": false,
        "scrollY": "300px", //dt高度
        "bLengthChange": false, //屏蔽tables的一页展示多少条记录的下拉列表
        "responsive": true, //自适应
        "searching": true, //本地搜索
        //          "bFilter": false, //列筛序功能
        "fixedHeader": true, //表头固定
        //          "bPaginate": true, //翻页功能
        //          "Info": true,//页脚信息
        "oLanguage": { //对表格国际化
            "sLengthMenu": "每页显示 _MENU_条",
            "sZeroRecords": "没有找到符合条件的数据",
            "sProcessing": "努力加载中",
            "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
            "sInfoEmpty": "没有数据",
            "sSearch": "查询：",
            "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            }
        },
        initComplete: function () { //列筛选
            var api = this.api();
            api.columns().indexes().flatten().each(function (i) {
                var column = api.column(i);
                var $span = $('<span style="width:60px;" class="addselect">▾</span>').appendTo($(column.header()))
                var select = $('<select style="outline: none;font-size:14px;width:60px;border: 1px solid #e5e5e5;background-color: #ffffff;"><option value="">全部</option></select>')
                    .appendTo($(column.header()))
                    .on('click', function (evt) {
                        evt.stopPropagation();
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        column
                            .search(val ? '^' + val + '$' : '', true, false)
                            .draw();
                    });
                column.data().unique().sort().each(function (d, j) {
                    function delHtmlTag(str) {
                        return str.replace(/<[^>]+>/g, ""); //去掉html标签
                    }

                    d = delHtmlTag(d)
                    select.append('<option value="' + d + '">' + d + '</option>')
                    $span.append(select)
                });
            });
        }
    });
    //行点击事件
    $('#queryMaterialTable tbody').on('click', 'tr', function () {
        var data = table.row(this).data();
        var id = data.id;
        page.getMaterialDetail(id);
    });
}